using UnityEditor;
using UnityEngine;
using UnityEngine.AI;

namespace com.yoozoo.gta.Gameplay.PVE
{
    public class NavmeshUnit
    {
        public int team;
        public float attackRange;

        public GameObject gameObject;
        private Animator animator;
        private NavMeshAgent agent;

        private NavmeshUnit target;
        
        public void Init()
        {
            #if UNITY_EDITOR
            gameObject =
                GameObject.Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(
                    "Assets/ResourcesAssets/Pve/Prefabs/Hero/m_HERO41001_Fu_M.prefab"));
            animator = gameObject.GetComponent<Animator>();
            #endif
            
            agent = gameObject.AddComponent<NavMeshAgent>();
        }


        private string m_action;
        private bool isInAttack;

        private void Play(string action)
        {
            /*if (m_action == action)
            {
                return;
            }*/
            if (!string.IsNullOrEmpty(m_action))
            {
                animator.ResetTrigger(m_action);
            }
            animator.SetTrigger(action);
            m_action = action;
        }

        public void Update()
        {
            if (isInAttack)
            {
                return;
            }
            if (target != null)
            {
                if (Vector3.Distance(target.gameObject.transform.position, gameObject.transform.position) <=
                    attackRange)
                {
                    isInAttack = true;
                    agent.SetDestination(gameObject.transform.position);
                    Play("MoveAttack");
                    //agent.autoBraking = false;
                    //agent.autoRepath = false;
                    //agent.autoTraverseOffMeshLink = false;
                    animator.SetFloat("AttackSpeed",1);
                    animator.SetFloat("WalkSpeed",0);
                }
                else
                {
                    agent.SetDestination(target.gameObject.transform.position);
                    Play("Run");
                    animator.SetFloat("WalkSpeed",1);
                }
                
            }
            else
            {
                target = NavmeshTestScene.Instance.GetTarget(team);
            }
        }
    }
}